home *** CD-ROM | disk | FTP | other *** search
- Path: hillres151.cc.purdue.edu!pacman
- From: pacman@hillres151.cc.purdue.edu (PacMan)
- Newsgroups: comp.lang.c
- Subject: Re: Can you printf a long
- Date: 4 Apr 1996 19:09:24 GMT
- Organization: prohibited
- Message-ID: <4k16p4$p28@mozo.cc.purdue.edu>
- References: <4ju8o1$dc3@news.netam.net>
- NNTP-Posting-Host: hillres151.cc.purdue.edu
-
- The Bowling Green Connection <bgc@alpha.netam.net> wrote:
- :I had some trouble with this code:
- :(I'm using gcc on Digital Unix)
- :
- [snip]
- : long i;
- [snip]
- : printf("%f\n", i);
- [snip]
-
- %f is for floats, not longs.
-
- :But when I changed %f to %d, the numbers printed correctly.
-
- %d is better than %f, but what you should have done was use %ld. The l
- means "long". Similarly, an h can be used to mean short, as in %hd.
-
- :I thought that %d had the same limitations as an int..that is,
- There you are correct. %d is for ints.
-
- :it could only print about 4 bits of information, whereas a long
- An int is supposed to be the natural word size of the machine. On 32-bit
- machines, it should be 32 bits. This is also OS/compiler dependent-- old
- MSloss compilers still use 16-bit ints on 32-bit machines. In any case,
- though, %d is the correct printf/scanf specifier for ints, and %ld for
- longs.
-
- :is capable of more (8 or 16 bits),
- longs might be bigger than ints, or they might not. (K&R2 p.196)
-
- : so wouldn't %f (float) be able
- :to better handle those long numbers?
- Here's where you really lost it: long,int,short,and char are all integer
- types. float and double are something completely different. Don't mix them
- unless you're sure you know what you're doing.
-
- : And why did %d work
- :correctly, even up to 634,000 (that's when my disk space ran out.. :))
- %d worked correctly because you happened to be on a system whose longs are
- the same as its ints. %ld would be the "most correct" conversion string.
-
- :
- :Well, then I changed the "long i" declaration to "int i", and changed %f
- :to %d, and I got the SAME results! The numbers went up to 634,000!
- :I didn't think an int could handle this much!
- On most systems, it can.
-
- :
- :Another strange thing is, I did a sizeof(int) and a sizeof(long), and they
- :BOTH returned a 4!!! That can't be right, can it??!
- It can. see again K&R2 p.196 and also p257 and your system's <limits.h>
- --
- Alan Curry
- -----BEGIN GEEK CODE BLOCK-----
- Version: 3.1
- GCS d? s++:-- a--- C+++ UL++++ P+ L+++>++++ E--- W-- N++ o K? w--- O? M--
- V? PS+ PE+ Y+ PGP- t* 5++ X+++ R- tv++ b- DI- D++ G+++ !e h! r-->+++ y?
- ------END GEEK CODE BLOCK------
-